﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionAppTest.SqlBuilder
{
    public static class SqlHelperExtension
    {
        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <param name="expr"></param>
        public static string GetBatchDeleteSql<T>(this IQueryable<T> entities, Expression<Func<T, bool>> expr)
        {
            ConditionBuilderVisitor visitor = new ConditionBuilderVisitor();
            visitor.Visit(expr);
            string condition = visitor.Condition();

            string sql = string.Format("DELETE FROM [{0}] WHERE {1};"
                , typeof(T).Name//有可能还得根据泛型去获取
                , condition);
            //然后执行sql
            return sql;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <param name="expr"></param>
        public static string GetQueryableSql<T>(this IEnumerable<T> entities, Expression<Func<T, bool>> expr)
        {
            ConditionBuilderVisitor visitor = new ConditionBuilderVisitor();
            visitor.Visit(expr);
            string condition = visitor.Condition();

            string sql = string.Format("Select * FROM [{0}] WHERE {1};"
                , typeof(T).Name
                , condition);
            return sql;
        }
    }
}
